const plugin = requirePlugin("WechatSI")

Page({
  data: {
    medicine: null,
    isRecording: false,
    voiceSuccess: false,
    reminderSet: false,
    askingReminder: false,  // 控制是否显示提醒相关提示文字
    reminderMessage: '',
    currentStep: 'initial'  // 用于追踪当前交互步骤
  },

  onLoad: function(options) {
    if (options.code) {
      this.getMedicineInfo(options.code);
    }
  },

  getMedicineInfo(code) {
    this.setData({ loading: true });
    
    // 模拟药品数据
    const mockData = {
      '6901234567890': {
        name: '开瑞坦',
        tradeName: '开瑞坦',
        manufacturer: '杭州默沙东制药有限公司',
        specification: '10mg*6片/盒',
        type: '片剂',
        approvalNumber: '国药准字H20171298',
        effects: '适用于缓解过敏性鼻炎症状，如喷嚏、流涕、鼻痒、鼻塞等。',
        contraindications: '对本品及其成分过敏者禁用。孕妇及哺乳期妇女慎用。'
      }
    };

    // 模拟查询延迟
    setTimeout(() => {
      if (mockData[code]) {
        this.setData({
          medicine: mockData[code],
          loading: false
        }, () => {
          // 先播放药品信息
          this.playMedicineInfo();
        });
      } else {
        this.setData({
          loading: false,
          medicine: null
        });
      }
    }, 1000);
  },

  playMedicineInfo() {
    if (!this.data.medicine) return;
    
    const { name, effects } = this.data.medicine;
    const content = `${name}。${effects}`;
    
    this.playVoice(content).then(() => {
      // 药品信息播放完后，延迟1秒询问是否需要提醒
      setTimeout(() => {
        this.askForReminder();
      }, 1000);
    });
  },

  askForReminder() {
    this.playVoice("需要我提醒您服药吗？").then(() => {
      // 模拟用户2秒后回答"需要"
      setTimeout(() => {
        this.simulateUserResponse();
      }, 2000);
    });
  },

  simulateUserResponse() {
    // 模拟用户语音输入状态
    this.setData({ simulatingVoice: true });
    
    // 1秒后显示提醒设置界面并询问时间
    setTimeout(() => {
      this.setData({ 
        showReminder: true,
        simulatingVoice: false
      });
      this.askForReminderTime();
    }, 1000);
  },

  askForReminderTime() {
    this.playVoice("请告诉我每周哪几天？每天几点提醒您").then(() => {
      // 模拟用户3秒后设置时间
      setTimeout(() => {
        this.simulateTimeResponse();
      }, 3000);
    });
  },

  simulateTimeResponse() {
    // 模拟用户语音输入状态
    this.setData({ simulatingVoice: true });
    
    // 2秒后显示设置成功
    setTimeout(() => {
      const message = "每周一、三、五中午11点的服药提醒已设置成功";
      this.setData({
        simulatingVoice: false,
        reminderSet: true,
        reminderMessage: message
      });
      
      // 播放设置成功的语音提示
      this.playVoice("每周一、三、五中午11点的服药提醒已设置，届时将通过电话提醒您");
      
      // 3秒后恢复正常状态
      setTimeout(() => {
        this.setData({ 
          reminderSet: false,
          showReminder: false 
        });
      }, 3000);
    }, 2000);
  },

  playVoice(content) {
    return new Promise((resolve, reject) => {
      plugin.textToSpeech({
        lang: "zh_CN",
        tts: true,
        content: content,
        voiceType: 1,
        speed: 0.8,
        volume: 0.8,
        success: (res) => {
          const innerAudioContext = wx.createInnerAudioContext();
          innerAudioContext.src = res.filename;
          innerAudioContext.play();
          
          innerAudioContext.onEnded(() => {
            innerAudioContext.destroy();
            resolve();
          });
        },
        fail: reject
      });
    });
  },

  // 长按开始录音
  handleVoiceBtnTouchStart() {
    this.setData({ 
      isRecording: true,
      voiceSuccess: false 
    });
    
    const recorderManager = wx.getRecorderManager();
    
    recorderManager.onStart(() => {
      console.log('开始录音');
    });

    recorderManager.start({
      duration: 60000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    });
  },

  // 松开结束录音
  handleVoiceBtnTouchEnd() {
    this.setData({ isRecording: false });
    
    const recorderManager = wx.getRecorderManager();
    recorderManager.stop();
    
    recorderManager.onStop((res) => {
      // 根据当前步骤处理语音识别结果
      if (this.data.currentStep === 'initial') {
        // 第一次语音交互后，显示提醒设置相关提示
        this.setData({
          askingReminder: true,
          currentStep: 'askingReminder'
        });
      } else if (this.data.currentStep === 'askingReminder') {
        // 设置提醒后显示成功消息
        this.setData({
          reminderSet: true,
          reminderMessage: "提醒已设置：每周一、三、五中午11点",
          askingReminder: false
        });
        
        // 3秒后清除成功提示
        setTimeout(() => {
          this.setData({
            reminderSet: false,
            currentStep: 'completed'
          });
        }, 3000);
      }
    });
  },

  // 防止页面自动返回
  onUnload() {
    // 停止语音播放
    if (this.data.isPlaying) {
      const innerAudioContext = wx.createInnerAudioContext();
      innerAudioContext.stop();
      this.setData({ isPlaying: false });
    }
  },

  backToScan() {
    // 如果正在播放语音，先停止
    if (this.data.isPlaying) {
      const innerAudioContext = wx.createInnerAudioContext();
      innerAudioContext.stop();
      this.setData({ isPlaying: false });
    }
    // 返回上一页（扫码页）
    wx.navigateBack({
      delta: 1
    });
  }
}); 